﻿using AutoMapper;
using KayakMes.Check.Application.Input;
using KayakMes.Check.Domain;
using KayakMes.Common;
using KayakMes.Common.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using KayakMes.Common.Dtos.CheckDto;

namespace KayakMes.Check.Application
{
    /// <summary>
    /// 检测项目分类实现层
    /// </summary>
    public class CheckItemService : ICheckItemService
    {
        private readonly BaseReposiotry<CheckItemModel> _checkItemReposiotry;   

        private readonly IMapper mapper;
        private static readonly object _codeLock = new object();

        public CheckItemService(BaseReposiotry<CheckItemModel> checkItemReposiotry, IMapper mapper)
        {
            _checkItemReposiotry = checkItemReposiotry;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加检查项
        /// </summary>
        /// <param name="checkItem"></param>
        /// <returns></returns>
        public ApiResult<int> AddCheckItem(AddCheckItemInput checkItem)
        {
            var model=mapper.Map<CheckItemModel>(checkItem);
            model.Id= YitIdHelper.NextId();
            model.CreateTime=DateTime.Now;
            var obj=   _checkItemReposiotry.Add(model);
            if(obj>0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "添加检查项目",
                    Data = obj
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "添加检查项目失败",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 获取检查项目
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<CheckItemModel> CheckItemModel(long Id)
        {
            var model = _checkItemReposiotry.GetModel(Id);
            return new ApiResult<CheckItemModel>
            {
                Code = ApiEnums.Success,
                Message = "查询成功",
                Data = model
            };
        }
        /// <summary>
        /// 删除检测项
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> DeleteCheckItem(long Id)
        {
            var model=_checkItemReposiotry.GetModel(Id);
            var obj=  _checkItemReposiotry.Delete(model);
            if(obj>0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "删除成功",
                    Data = obj
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "删除失败",
                    Data = obj
                };
            }

          
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiPaging<CheckItemModel> GetAllCheckItem(CheckItemInput input)
        {
          
                // 1. 构建基础查询，并排除已软删除的数据
                var query = _checkItemReposiotry.GetAll().Where(x => !x.IsDeleted);

                // 2. 应用筛选条件（模糊查询）
                if (!string.IsNullOrEmpty(input.CheckItemCode))
                    query = query.Where(x => x.CheckItenCode.Contains(input.CheckItemCode));

                if (!string.IsNullOrEmpty(input.CheckItemName))
                    query = query.Where(x => x.CheckItemName.Contains(input.CheckItemName));

            

                // 3. 在分页前获取总记录数
                var total = query.Count();

                // 4. 应用排序和分页，直接获取实体列表
                var items = query.OrderByDescending(x => x.CreateTime)
                                 .Skip((input.PageIndex - 1) * input.PageSize)
                                 .Take(input.PageSize)
                                 .ToList();
                
                // 5. 构建并返回标准分页结果，直接使用实体列表
                return new ApiPaging<CheckItemModel>
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Items = items, // 直接返回实体列表
                    Total = total,
                    PageIndex = input.PageIndex,
                    PageSize = input.PageSize
                };
            
          
        }
        /// <summary>
        /// 随机生成检测项目编号
        /// </summary>
        /// <returns>格式为 PC001 的字符串</returns>
        public string GetCheckItemCode()
        {
            lock (_codeLock)
            {
                var maxCode = _checkItemReposiotry.GetAll()
                    .Where(x => !string.IsNullOrEmpty(x.CheckItenCode) && x.CheckItenCode.StartsWith("PC"))
                    .OrderByDescending(x => x.CheckItenCode)
                    .Select(x => x.CheckItenCode)
                    .First();

                int nextNumber = 1;

                if (!string.IsNullOrWhiteSpace(maxCode))
                {
                    var numPart = maxCode.Substring(2); 
                    if (int.TryParse(numPart, out int currentNum))
                    {
                        nextNumber = currentNum + 1;
                    }
                }
                
                return $"PC{nextNumber:D3}";
            }
        }
        /// <summary>
        /// 修改检测项目
        /// </summary>
        /// <param name="checkItem"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateCheckItem(UpdateChenitemInput checkItem)
        {
            var model = _checkItemReposiotry.GetModel(checkItem.Id);
            
            mapper.Map(checkItem, model);
            var result = _checkItemReposiotry.Update(model);
            if(result>0)
            {
                return new ApiResult<int>
                {
                    Code=ApiEnums.Success,
                    Message="修改成功",
                    Data=result
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Code=ApiEnums.Fail,
                    Message="修改失败",
                    Data=result
                };
            }
        }
    }
}
